<template>
  <div>
    <!-- 搜索 -->
    <TopFilter ref="TopFilterss" :list="topFilterInit" :cols="3" :collapse="collapse" labelWidth="110" @filterChange="changeHandle"></TopFilter>
    <!-- table -->
    <FilterTable
      ref="table"
      :columns="columns"
      :params="fetchParams"
      :fetchapi="fetchapi"
      :datakey="'records'"
      :onColumnsChange="(columns) => (this.columns = columns)"
      :isSelectColumn="false"
    >
     <template slot="controls" slot-scope="props">
       <div style="padding-top: 1rem;"></div>
       <el-button size="small" type="text" style="font-size: 14px; color: #bb2801; font-weight: bold">
         <span >每月{{start}}-{{end}}日可维护此界面</span>
       </el-button>
        <multiuse-button type="primary" @click="addShow" :disabled="flag">新增</multiuse-button>
        <multiuse-button type="primary" @click="exportFileBtn">导出</multiuse-button>
      </template>
    </FilterTable>
    <Drawer :visible.sync="visibleAdd" :title="'发票新增'" destroyOnClose width="60%" :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}">
      <AddForm @close="closeAdd" @save="saveAdd"></AddForm>
    </Drawer>
     <Drawer :visible.sync="visibleEdit" :title="'发票编辑'" destroyOnClose width="60%" :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}">
      <EditForm @close="closeEdit" @save="saveEdit" :rowData="rowData"></EditForm>
    </Drawer>
    <Drawer :visible.sync="detailFlag" :title="'发票详情'" destroyOnClose width="60%" :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}">
      <DetailForm @close="detailclose" @save="detailsave" :rowData="rowData"></DetailForm>
    </Drawer>
  </div>
</template>
<script>
import moment from "moment";
import EditForm from './EditForm.vue';
import AddForm from './AddForm.vue';
import DetailForm from './DetailForm.vue';
import { getPartType,getListByPage,deleteOne ,submitById,getListForExport,exporturl} from '@/api/claim/dealer/InvoiceManage';
// import { getPartType } from '@/api/dictionary';
import { exportExcelFile } from '@/utils/index';
// 查询索赔基础参数发票维护日期
import { selectByParaCode, multiples } from '@/api/claim/factory/SystemParameterMaintain';
import { getAppId } from '@/assets/js/auth';
import { dictionary } from '@/utils/dictMixin';

export default {
  mixins: [dictionary],
  components: {
    EditForm,
    AddForm,DetailForm
  },
  data() {
    return {
      dataList: [],
      detailFlag: false,
      visible: false,
      visibleDrawer: false,
      collapse: true,
      infoId: null,
      topFilterInit: this.topFilterInitFun(),
      flterValue: {}, //参数
      rowData: {},
      fetchParams: {xhrAbort: true}, //ipa 接口
      selectedRows: [], //选中经销商
      dialogTitle: '选择车辆',
      visibleAdd: false,
      fetchapi: getListByPage,
      editRow: {},
      visibleEdit: false,
      columns: this.creatHeader(),
      flag:false,
      start:null,
      end:null
    };
  },
  async created() {
    if (getAppId() == 'arcfox') {
      this.topFilterInit.find(x => x.fieldName == 'carType').itemList =this.createDictList('5543',[55431001])
    }else{
      this.topFilterInit.find(x => x.fieldName == 'carType').itemList =this.createDictList('5543')
    }
    this.chuqi();
    const res = await selectByParaCode({ paraCode: 'XTCS00029'});
    var date = new Date();
    var day = date.getDate();
    this.start = res.data.para1;
    this.end = res.data.para2;
    if(day<res.data.para1 ||day>res.data.para2){
      this.flag = true;
    }else{
      this.flag = false;
    }
    this.fetchParams.invoiceDateStart = moment().startOf('week').format('YYYY-MM-DD HH:mm:ss');
    this.fetchParams.invoiceDateEnd = moment().endOf('week').format('YYYY-MM-DD HH:mm:ss');
  },
  methods: {
    // 导出
    async exportFileBtn() {
      let json = Object.assign({}, { CODE: 'CODE_00000207' }, this.fetchParams);
      let res = await exporturl(json);
      if (res.resultCode == 200) {
        this.$router.push('/admin/auth/oem/downloadCenter');
      }
      //     let beginCreatedAt = this.topFilterInit.find(x => x.fieldName == "invoiceDateStart|invoiceDateEnd").initialValue[0];
      // let endCreatedAt = this.topFilterInit.find(x => x.fieldName == "invoiceDateStart|invoiceDateEnd").initialValue[1];
      // if(!beginCreatedAt) {
      //   this.$notify.warning({ title: '提示信息', message: '创建开始日期不可为空！' });
      //   return
      // }
      // if(!endCreatedAt) {
      //   this.$notify.warning({ title: '提示信息', message: '创建结束日期不可为空！' });
      //   return
      // }
      // if(getAppId() == 'arcfox') {
      //   if (moment(moment(endCreatedAt).format('YYYY-MM-DD')).diff(moment(beginCreatedAt), 'months', true) > 12) {
      //     this.$notify.warning({ title: '提示信息', message: '开票日期跨度不可超过十二个月！' });
      //     return
      //   }
      // } else {
      //   if (moment(moment(endCreatedAt).format('YYYY-MM-DD')).diff(moment(beginCreatedAt), 'months', true) > 12) {
      //     this.$notify.warning({ title: '提示信息', message: '开票日期跨度不可超过十二个月！' });
      //     return
      //   }
      // }
      // let obj = Object.assign({}, this.fetchParams, {xhrAbort: false});
      // obj.invoiceDateStart = this.topFilterInit.find(x => x.fieldName == "invoiceDateStart|invoiceDateEnd").initialValue[0];
      // obj.invoiceDateEnd = this.topFilterInit.find(x => x.fieldName == "invoiceDateStart|invoiceDateEnd").initialValue[1];
      // getListForExport(obj).then(res => {
      //   exportExcelFile(res.data, '发票维护');
      // });
    },
    // 提交
    async submitFun(val) {
      this.$confirm('确定提交吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          val.batchStatus=55481002;
          this.res = await submitById( val );
          if (this.res.resultCode != 200) {
            this.$notify.error({ title: '提示信息', message: res.errMsg || '提交失败!' });
          } else {
            this.$notify.success({ title: '提示信息', message: '提交成功!' });
            this.fetchParams = { ...this.fetchParams };
          }
        })
    },
    // 删除
    async delFun(val) {
      this.$confirm('确定删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          this.res = await deleteOne( val.batchId );
          if (this.res.resultCode != 200) {
            this.$notify.error({ title: '提示信息', message: res.errMsg || '删除失败!' });
          } else {
            this.$notify.success({ title: '提示信息', message: '删除成功!' });
            this.fetchParams = { ...this.fetchParams };
          }
        })
    },
    //翻译
    async chuqi() {
      // const res = await getPartType({ type: 5548 });
      // delete  res.data[2]
      // delete  res.data[3]
      // if (res.resultCode == 200) {
      //   this.topFilterInit.find(x => x.fieldName == 'batchStatus').initialValue = '';
      //   this.topFilterInit.find(x => x.fieldName == 'batchStatus').itemList = res.data.map(y => ({ text: y.codeCnDesc, value: y.codeId }));
      // }


      // const res4 = await getPartType( {type:5543});
      // if (res4.resultCode == 200) {
      //
      //   if (getAppId() == 'arcfox') {
      //     delete res4.data[0];
      //   }
      //
      //   this.topFilterInit.find(x => x.fieldName == 'carType').initialValue = '';
      //   this.topFilterInit.find(x => x.fieldName == 'carType').itemList = res4.data.map(y =>({ text: y.codeCnDesc, value: y.codeId }));
      // }
    },
    async deleteHandle(row) {
      let res = await edit(row.destoryId);
      this.editRow = res.data;
      this.visibleEdit = true;
    },
    editFun(val) {
      this.rowData = val;
      this.visibleEdit = true;
    },
    showDetailFun(val)  {
      this.detailFlag = true;
      this.rowData = val;
    },
    //查看
    detailsave() {
      this.detailFlag = false;
      this.fetchParams = { ...this.fetchParams };
    },
    detailclose() {
      this.detailFlag = false;
      // this.fetchParams = { ...this.fetchParams };
    },
    //选中
    selectChange(rows) {
      this.selectedRows = rows;
      console.log(this.selectedRows);
    },
    close() {
      this.visible = false;
    },
    chooseOrderNo() {
      this.visible = true;
    },
    save(obj) {
      this.topFilterInit.find((x) => x.fieldName == 'model').initialValue = obj[0].address;
      this.visible = false;
    },
    addShow() {
      this.visibleAdd = true;
    },
    addClose() {
      this.visibleAdd = false;
      // this.fetchParams = { ...this.fetchParams };
    },
    saveEdit() {
      this.visibleEdit = false;
      this.fetchParams = { ...this.fetchParams };
    },
    closeEdit() {
      this.visibleEdit = false;
      // this.fetchParams = { ...this.fetchParams };
    },
    closeAdd() {
      this.visibleAdd = false;
      // this.fetchParams = { ...this.fetchParams };
    },
    saveAdd() {
      this.visibleAdd = false;
      this.fetchParams = { ...this.fetchParams };
    },
    //搜索获取数据
    changeHandle(val) {
      if(!val.invoiceDateStart) {
        this.$notify.warning({ title: '提示信息', message: '创建开始日期不可为空！' });
        return
      }
      if(!val.invoiceDateEnd) {
        this.$notify.warning({ title: '提示信息', message: '创建结束日期不可为空！' });
        return
      }
      if(getAppId() == 'arcfox') {
        if (moment(moment(val.invoiceDateEnd).format('YYYY-MM-DD')).diff(moment(val.invoiceDateStart), 'months', true) > 12) {
          this.$notify.warning({ title: '提示信息', message: '开票日期跨度不可超过十二个月！' });
          return
        }
      } else {
        if (moment(moment(val.invoiceDateEnd).format('YYYY-MM-DD')).diff(moment(val.invoiceDateStart), 'months', true) > 12) {
          this.$notify.warning({ title: '提示信息', message: '开票日期跨度不可超过十二个月！' });
          return
        }
      }
      this.fetchParams = Object.assign({}, this.fetchParams, val,{xhrAbort: false});
    },
    //搜索数据
    topFilterInitFun() {
      return [
        {type: 'INPUT', label: '发票号', fieldName: 'invoiceNo', placeholder: '请输入发票单号...', initialValue: ''},
        {
          type: 'RANGE_DATE',
          label: '创建时间',
          fieldName: 'invoiceDateStart|invoiceDateEnd',
          placeholder: '请输入',
          initialValue: [
            moment()
              .startOf('week')
              .format('YYYY-MM-DD HH:mm:ss'),
            moment()
              .endOf('week')
              .format('YYYY-MM-DD HH:mm:ss')
          ],
          rules: [{ required: true, message: '请选择日期', trigger: 'change' }]
        },
        {type: 'INPUT', label: '结算单号', fieldName: 'settleNo', placeholder: '请输入结算单号...', initialValue: ''},
        { type: 'SELECT', label: '索赔车辆属性', fieldName: 'carType', placeholder: '请选择索赔车辆属性...', initialValue: '',itemList: [] }

      ];
    },
    //table表头和数据源
    creatHeader() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          fixed: 'left',
          render: (props) => {
            return <span>{props.row.index + 1}</span>;
          },
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 200,
          render: (props) => {
            return (
              <div style="text-align:center">
                <multiuse-button size="mini" type="text"  disabled={((props.row.batchStatus == '55481002')|| (props.row.batchStatus =='55481003')|| (props.row.batchStatus =='55481004')|| (props.row.batchStatus =='55481006') )? true:false } onClick={() => this.editFun(props.row)}>
                  编辑
                </multiuse-button>
                <multiuse-button size="mini" type="text"  disabled={(props.row.batchStatus == '4444')? true:false } onClick={() => this.showDetailFun(props.row)}>
                  明细
                </multiuse-button>
                  <multiuse-button size="mini" type="text" disabled={((props.row.batchStatus == '55481002')|| (props.row.batchStatus =='55481003')|| (props.row.batchStatus =='55481004')|| (props.row.batchStatus =='55481006') ||this.flag)? true:false } onClick={() => this.delFun(props.row)}>
                  删除
                </multiuse-button>
                <multiuse-button size="mini" type="text" disabled={((props.row.batchStatus == '55481002')|| (props.row.batchStatus =='55481003')|| (props.row.batchStatus =='55481004')|| (props.row.batchStatus =='55481006') ||this.flag)? true:false }  onClick={() => this.submitFun(props.row)}>
                  提交
                </multiuse-button>
              </div>
            );
          },
        },
        {title: '发票号', dataIndex: 'invoiceNo', sorter: true},
        {title: '结算批次号', dataIndex: 'batchNo', sorter: true},
        {title: '结算单号', dataIndex: 'settleNo', sorter: true},
        {title: '结算单状态', dataIndex: 'statusStr', sorter: true},
        {title: '索赔车辆属性', dataIndex: 'carTypeStr', sorter: true},
        {title: '索赔单数', dataIndex: 'claimNum', sorter: true},
        {title: '发票张数', dataIndex: 'invoiceSheets', sorter: true},
        {title: '工时费', dataIndex: 'labourAmount', sorter: true},
        {title: '配件费', dataIndex: 'partAmount', sorter: true},
        {title: '附加费', dataIndex: 'addAmount', sorter: true},
        {title: '一口价费用', dataIndex: 'priceAmount', sorter: true},
        {title: '邮寄时间', dataIndex: 'sendDate', sorter: true},
        {title: '索赔金额', dataIndex: 'claimSum', sorter: true},
        {title: '考核金额', dataIndex: 'assessSum', sorter: true},
        {title: '开票金额', dataIndex: 'invoiceSum', sorter: true},
        {title: '税率', dataIndex: 'invoicePoint', sorter: true},
        {title: '税额', dataIndex: 'invoicePointAmount', sorter: true},
        {title: '金额', dataIndex: 'invoiceMoney', sorter: true},
        // { title: '邮寄时间', dataIndex: 'createdAt', sorter: true },
        {title: '审核时间', dataIndex: 'approveDate', sorter: true},
        {title: '开票时间', dataIndex: 'submitDate', sorter: true}
      ];
    },
  },
};
</script>

<style lang="less" scoped></style>
